﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Threading;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone.Scheduler;
using System.Windows.Threading;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Shell;
using ShellUiHelpers;
using Microsoft.Live;
using System.Windows.Navigation;

namespace WorkTime_pan
{
    public partial class MainPage : PhoneApplicationPage
    {
        // хранилище настроек
        public static IsolatedStorageSettings settings;
        const string PositionTask = "Position-Task";

        private GeoCoordinateWatcher _myGeoWatcher;
        const string Currentcoordinata_Name  = "Currentcoordinata";
        const string Selectedcoordinata_Name = "Selectedcoordinata";
        public GeoCoordinate Selectedcoordinata_default = new GeoCoordinate(60,30);

        const string periodicTaskOnName = "PeriodicTaskOn";
        static bool periodicTaskOn_default = false;

        const string timeWorkName = "timeWork";
        const string timeWork_YesterdayName = "timeWork_Yesterday";
        const string timeWorkName_lastweek = "timeWork_lastweek";
        const string timeWorkName_lastmounth = "timeWork__lastmounth";

        TimeSpan timeWork_default = new TimeSpan();

        private Pushpin _myPushpin_selected;
        private Pushpin _myPushpin_current;

        // текущая координата
        public GeoCoordinate Currentcoordinata
        {
            get
            {
                return GetValueOrDefault<GeoCoordinate>(Currentcoordinata_Name, Selectedcoordinata_default);
            }
            set
            {
                if (AddOrUpdateValue(Currentcoordinata_Name, value))
                {
                    settings.Save();
                }
            }
        }
        // выбранная координата
        public GeoCoordinate Selectedcoordinata
        {
            get
            {
                return GetValueOrDefault<GeoCoordinate>(Selectedcoordinata_Name, Selectedcoordinata_default);
            }
            set
            {
                if (AddOrUpdateValue(Selectedcoordinata_Name, value))
                {
                    settings.Save();
                }
            }
        }
        public static bool periodicTaskOn
        {
            get
            {
                return GetValueOrDefault<bool>(periodicTaskOnName, periodicTaskOn_default);
            }
            set
            {
                if (AddOrUpdateValue(periodicTaskOnName, value))
                {
                    settings.Save();
                }
            }
        }
        public static bool disablecheck
        {
            get
            {
                return GetValueOrDefault<bool>("disablecheck", periodicTaskOn_default);
            }
            set
            {
                if (AddOrUpdateValue("disablecheck", value))
                {
                    settings.Save();
                }
            }
        }

        // время работы
        public TimeSpan timework
        {
            get
            {
                return GetValueOrDefault<TimeSpan>(timeWorkName, timeWork_default);
            }
            set
            {
                if (AddOrUpdateValue(timeWorkName, value))
                {
                    settings.Save();
                }
            }
        }
        // время работы за вчера
        public TimeSpan timework_Yesterday
        {
            get
            {
                return GetValueOrDefault<TimeSpan>(timeWork_YesterdayName, timeWork_default);
            }
            set
            {
                if (AddOrUpdateValue(timeWork_YesterdayName, value))
                {
                    settings.Save();
                }
            }
        }
        // время работы за неделю
        public TimeSpan timework_lastweek
        {
            get
            {
                return GetValueOrDefault<TimeSpan>(timeWorkName_lastweek, timeWork_default);
            }
            set
            {
                if (AddOrUpdateValue(timeWorkName_lastweek, value))
                {
                    settings.Save();
                }
            }
        }
        // время работы за неделю
        public TimeSpan timework_lastmounth
        {
            get
            {
                return GetValueOrDefault<TimeSpan>(timeWorkName_lastmounth, timeWork_default);
            }
            set
            {
                if (AddOrUpdateValue(timeWorkName_lastmounth, value))
                {
                    settings.Save();
                }
            }
        }
        // время последнего обновления
        public DateTime time
        {
            get
            {
                return GetValueOrDefault<DateTime>("lasttime", DateTime.Now);
            }
            set
            {
                if (AddOrUpdateValue("lasttime", value))
                {
                    settings.Save();
                }
            }
        }

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            settings = IsolatedStorageSettings.ApplicationSettings;

            // определим текущие координаты
            _myGeoWatcher = new GeoCoordinateWatcher();
            _myGeoWatcher.MovementThreshold = 50.0f;
            _myGeoWatcher.StatusChanged += MyGeoWatcherStatusChanged;
            _myGeoWatcher.PositionChanged += MyGeoWatcherPositionChanged;

            Coordinata.Text = Selectedcoordinata.Latitude.ToString() + " " + Selectedcoordinata.Longitude.ToString();
            Yesterday.Text = "Вчера " + ((int)(timework_Yesterday.TotalHours)).ToString() + " часов " + timework_Yesterday.Minutes.ToString() + " мин";
            last_week.Text = "За неделю " + ((int)(timework_lastweek.TotalHours)).ToString() + " часов " + timework_lastweek.Minutes.ToString() + " мин";
            last_mouth.Text = "За месяц " + ((int)(timework_lastmounth.TotalHours)).ToString() + " часов " + timework_lastmounth.Minutes.ToString() + " мин";

            MyMap.Tap += new EventHandler<GestureEventArgs>(MyMap_Tap);

            _myPushpin_selected = new Pushpin();
            _myPushpin_selected.Content = "Следить здесь";

            _myPushpin_selected.Location = Selectedcoordinata;

            if (!MyMap.Children.Contains(_myPushpin_selected))
            {
                MyMap.Children.Add(_myPushpin_selected);
            }

            _myPushpin_current = new Pushpin();
            _myPushpin_current.Content = "Я";

            DispatcherTimer systimer = new DispatcherTimer();
            systimer.Interval = TimeSpan.FromSeconds(10);
            systimer.Tick += SysTimeTick;
            systimer.Start();

            // обновим текст на экране с координатами
            CurrentCoordinata.Text = Currentcoordinata.Latitude.ToString() + " " + Currentcoordinata.Longitude.ToString();
            UpdateWorkState();

            DisableEdit.IsChecked = disablecheck;
        }

        private void SysTimeTick(object sender, EventArgs e)
        {
            // обновим текущее состояние: на работе или нет?
            UpdateWorkState();

            // запустим определение координат
            _myGeoWatcher.TryStart(false, TimeSpan.FromSeconds(10));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
        }

        void UpdateWorkState()
        {
            bool OnWork = false;

            if (Currentcoordinata.Latitude < Selectedcoordinata.Latitude + 0.0025 && Currentcoordinata.Latitude > Selectedcoordinata.Latitude - 0.0025)
            {
                if (Currentcoordinata.Longitude < Selectedcoordinata.Longitude + 0.0025 && Currentcoordinata.Longitude > Selectedcoordinata.Longitude - 0.0025)
                {
                    // на работе
                    Work_or_not.Text = "на работе";
                    timeWork.Text = timework.ToString();

                    OnWork = true;

                    timeWork1.Visibility = Visibility.Collapsed;
                    timeWork2.Visibility = Visibility.Collapsed;

                    TimeSpan span1 = new TimeSpan(time.Day, time.Hour, time.Minute, time.Second);
                    TimeSpan span2 = new TimeSpan(DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

                    // на работе
                    timework += (span2 - span1);
                    timework_lastweek += (span2 - span1);
                    timework_lastmounth += (span2 - span1);
                }
                else 
                {
                    Work_or_not.Text = "ушел";
                    timeWork.Text = "c работы";
                    timeWork2.Text = timework.ToString();

                    timeWork1.Visibility = Visibility.Visible;
                    timeWork2.Visibility = Visibility.Visible;
                }
            }
            else 
            { 
                Work_or_not.Text = "ушел";
                timeWork.Text = "c работы"; 
                timeWork2.Text = timework.ToString();

                timeWork1.Visibility = Visibility.Visible;
                timeWork2.Visibility = Visibility.Visible;
            }

            // запомним текущее время
            time = DateTime.Now;

            if (disablecheck)
            {
                
            }

            Yesterday.Text = "Вчера " + ((int)(timework_Yesterday.TotalHours)).ToString() + " часов " + timework_Yesterday.Minutes.ToString() + " мин";
            last_week.Text = "За неделю " + ((int)(timework_lastweek.TotalHours)).ToString() + " часов " + timework_lastweek.Minutes.ToString() + " мин";
            last_mouth.Text = "За месяц " + ((int)(timework_lastmounth.TotalHours)).ToString() + " часов " + timework_lastmounth.Minutes.ToString() + " мин";

            {   //Тайл изменим
                string work;
                string work_time;

                if (OnWork == true)
                {
                    work = "на работе";
                    work_time = timework.ToString();
                }
                else
                {
                    work = "ушел";
                    work_time = "с работы";
                }

                TileHelper.UpdateTile(" ", work_time, null, null);
            }
        }

        void MyGeoWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Currentcoordinata = _myGeoWatcher.Position.Location;
            
            // обновим текст на экране с координатами
            CurrentCoordinata.Text = Currentcoordinata.Latitude.ToString() + " " + Currentcoordinata.Longitude.ToString();

            MyMap.SetView(Currentcoordinata, 15);

            _myPushpin_current.Location = Currentcoordinata;

            if (!MyMap.Children.Contains(_myPushpin_current))
            {
                MyMap.Children.Add(_myPushpin_current);
            }

            // обновим текущее состояние: на работе или нет?
            UpdateWorkState();
        }

        void MyGeoWatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    if (_myGeoWatcher.Permission == GeoPositionPermission.Denied)
                    {
                        GeoStatus.Text = "GPS: Сервис выключен";
                    }
                    else
                    {
                        GeoStatus.Text = "GPS: На этом устройстве сервис недоступен";
                    }
                break;
                case GeoPositionStatus.Initializing:
                    GeoStatus.Text = "GPS: Сервис инициализируется";
                break;
                case GeoPositionStatus.NoData:
                    GeoStatus.Text = "GPS: Данные о местоположении недоступны";
                break;
                case GeoPositionStatus.Ready:
                    GeoStatus.Text = "GPS: Данные о местоположении доступны";
                break;
            }
        }

        void MyMap_Tap(object sender, GestureEventArgs e)
        {
            if (disablecheck) return;

            _myPushpin_selected.Location = MyMap.Center;
            Selectedcoordinata  = MyMap.Center;

            if (!MyMap.Children.Contains(_myPushpin_selected))
            {
                MyMap.Children.Add(_myPushpin_selected);
            }

            Coordinata.Text = Selectedcoordinata.Latitude.ToString() + " " + Selectedcoordinata.Longitude.ToString();

            // обновим текущее состояние: на работе или нет?
            UpdateWorkState();
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void StartTask_Click(object sender, RoutedEventArgs e)
        {
            if (disablecheck) return;

            /*PeriodicTask myPeriodicTask = ScheduledActionService.Find(PositionTask) as PeriodicTask;

            if (periodicTaskOn == false)
            { // задача не запущена
                StartTask.Content = "Останов слежения";
                periodicTaskOn = true;

                myPeriodicTask = new PeriodicTask(PositionTask);
                myPeriodicTask.Description = "Position-Task";

                try
                {
                    ScheduledActionService.Add(myPeriodicTask);
#if DEBUG
                    ScheduledActionService.LaunchForTest(PositionTask, TimeSpan.FromSeconds(10));
#endif
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Невозможно создать сервис:" + ex.Message);
                }
            }
            else
            {
                StartTask.Content = "Старт слежения";
                periodicTaskOn = false;

                if (myPeriodicTask != null)
                {
                    try
                    {
                        ScheduledActionService.Remove(PositionTask);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Невозможно удалить ранее созданный сервис:" + ex.Message);
                    }
                }
            }*/
        }

        // сохранение параметров
        public static bool AddOrUpdateValue(string Key, Object value)
        {
            bool valueChanged = false;

            // If the key exists
            if (settings.Contains(Key))
            {
                // If the value has changed
                if (settings[Key] != value)
                {
                    // Store the new value
                    settings[Key] = value;
                    valueChanged = true;
                }
            }
            // Otherwise create the key.
            else
            {
                settings.Add(Key, value);
                valueChanged = true;
            }
            return valueChanged;
        }

        public static T GetValueOrDefault<T>(string Key, T defaultValue)
        {
            T value;

            // If the key exists, retrieve the value.
            if (settings.Contains(Key))
            {
                value = (T)settings[Key];
            }
            // Otherwise, use the default value.
            else
            {
                value = defaultValue;
            }
            return value;
        }

        private void ClearCounters_Click(object sender, RoutedEventArgs e)
        {
            if (disablecheck) return;

            timework = new TimeSpan(0, 0, 0, 0);
            timework_lastweek = new TimeSpan(0, 0, 0, 0);
            timework_lastmounth = new TimeSpan(0, 0, 0, 0);
        }

        private void Journal_Click(object sender, RoutedEventArgs e)
        {   // чтение журнала
            this.NavigationService.Navigate(new Uri("/jornalPage.xaml", UriKind.Relative));
        }

        private void SkyDrive_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/SkyDriveBackup.xaml", UriKind.Relative));
        }

        private void Current_Click(object sender, RoutedEventArgs e)
        {
            MyMap.SetView(Currentcoordinata, 15);
        }

        private void Current1_Click(object sender, RoutedEventArgs e)
        {
            MyMap.SetView(Selectedcoordinata, 15);
        }

        private void DisableEdit_Checked(object sender, RoutedEventArgs e)
        {
            disablecheck = (bool)DisableEdit.IsChecked;
        }

    }
}